import { InputOption, PatternInputItemOption, RollifyConfigure } from '../typing'

import { isFunction, isObject, isString, merge } from 'node-aux'
import { parseGlob } from '../utils/parse'

const setInput = function (entry: PatternInputItemOption) {
    const { pattern, filename, ignore, patternOptions, inputConfig } = entry
    const entryList = parseGlob(pattern, ignore, patternOptions)
    if (pattern) {
        const inputObj: Record<string, string> = {}
        entryList.forEach((item) => {
            const { starValue, path } = item
            if (!starValue) {
                return
            }
            inputObj[starValue] = path
        })
        return merge(inputObj, inputConfig)
    }
    if (filename && isString(filename)) {
        return filename
    }
    if (isFunction(filename)) {
        return filename(entryList)
    }
    if (isObject(entry) && !pattern && !filename) {
        return entry
    }
    return
}

export const transformInput = function (libType?: 'pattern' | 'original', entry?: InputOption) {
    if (libType === 'pattern') {
        if (isObject(entry)) {
            return setInput(entry as PatternInputItemOption)
        }
        if (isString(entry)) {
            return setInput({ pattern: entry } as unknown as PatternInputItemOption)
        }
        return entry
    }
    return entry
}

export const inputConfigure = function <T extends RollifyConfigure>(userConfig: T) {
    const { entry, libType } = userConfig
    return {
        name: 'input',
        configure: () => {
            return transformInput(libType, entry)
        }
    }
}
